const path = require("path");
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const sha1 = require("sha1");
const { response } = require("express");
const { title } = require("process");
const { default: axios } = require("axios");
// const { init: initDB, Counter } = require("./db");
const logger = morgan("tiny");
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors());
app.use(logger);
var parseString = require('xml2js').parseString;
let accessToken 
// 引入express模块
var config = {
    "appID": "wx163c1f019c9b0082",
    "appsecret": "877b980ecb0cf1ee9dccac9fd8cacf1f",
    "token": "wechat"   
}
var createMenu = async function(){
  let data = await axios.post(`https://api.weixin.qq.com/cgi-bin/menu/create?access_token=${accessToken}`,{
    data:{
      "button":[
        {	
             "type":"click",
             "name":"今日歌曲",
             "key":"V1001_TODAY_MUSIC"
         },
         {
              "name":"菜单",
              "sub_button":[
              {	
                  "type":"view",
                  "name":"搜索",
                  "url":"http://www.soso.com/"
               },
               {
                    "type":"miniprogram",
                    "name":"wxa",
                    "url":"http://mp.weixin.qq.com",
                    "appid":"wx286b93c14bbf93aa",
                    "pagepath":"pages/lunar/index"
                },
               {
                  "type":"click",
                  "name":"赞一下我们",
                  "key":"V1001_GOOD"
               }]
          }]
    }
  })
  console.log(data)
}
var getAccessToken =async function() {
  let url = 'https://api.weixin.qq.com/cgi-bin/token'
  let data = await axios.get(url,{
    params:{
      grant_type:'client_credential',
      appid:config.appID,
      secret:config.appsecret
    }
  })
  console.log(data.data.access_token)
  accessToken = data.data.access_token
}

app.get("/", (req, res, next)=> {
    // 获取微信服务器发送的数据
    console.log("i am comming")
    var signature = req.query.signature
    var timestamp = req.query.timestamp
    var nonce = req.query.nonce
    var echostr = req.query.echostr;
    // token、timestamp、nonce三个参数进行字典序排序
    var arr = [config.token, timestamp, nonce].sort().join('');
    // sha1加密    
    var result = sha1(arr);
    if(result === signature){
        res.send(echostr);
    }else{
        res.send('mismatch');
    }
})
const store = {
  "浙江工商大学1":{
    title:"浙江工商大学",
    description:"浙江工商大学（Zhejiang Gongshansg University），简称“浙商大”（ZJSU），坐落于浙江省杭州市，是中华人民共和国教育部、中华人民共和国商务部和浙江省人民政府共建的浙江省重点建设高校，",
    picurl:"https://mmbiz.qpic.cn/mmbiz_png/BQW5dvHDwl3tGlgv7XiciaX9Wg0GgxjF1VQ3c27rZA9aUObZZpwtZDjEwv2BDic7gfnvzrKBWicG9Hvpe25Gmribe5A/0?wx_fmt=png",
    url:"https://mp.weixin.qq.com/s?__biz=MzI5NTI5NTA3NA==&mid=2247483658&idx=1&sn=7d3f050b2221eb600136b254a44ee8c6&chksm=ec548007db230911233b08120491f83cc9367f598478faa5e98bbce9d49c779a356554c26930&token=1396383552&lang=zh_CN#rd"
  }
}
function createTextRes (fromUser, toUser, msg){
  var resultXml =  "<xml><ToUserName><![CDATA["+ fromUser +"]]></ToUserName>";
  resultXml += "<FromUserName><![CDATA["+ toUser +"]]></FromUserName>";
  resultXml += "<CreateTime>"+ new Date().getTime() +"</CreateTime>";
  resultXml += "<MsgType><![CDATA[text]]></MsgType>";
  resultXml += "<Content><![CDATA["+msg+"]]></Content></xml>";
  return resultXml
}
function createOneArticleRes(fromUser, toUser, title, Description,PicUrl,Url){
  var resultXml = `
  <xml>
    <ToUserName><![CDATA[${toUser}]]></ToUserName>
    <FromUserName><![CDATA[${fromUser}]]></FromUserName>
    <CreateTime>${new Date().getTime()}</CreateTime>
    <MsgType><![CDATA[news]]></MsgType>
    <ArticleCount>1</ArticleCount>
    <Articles>
      <item>
        <Title><![CDATA[${title}]]></Title>
        <Description><![CDATA[${Description}]]></Description>
        <PicUrl><![CDATA[${PicUrl}]]></PicUrl>
        <Url><![CDATA[${Url}]]></Url>
      </item>
    </Articles>
  </xml>
  `
  return resultXml
}
app.post("/", (req,res, next)=> {
  var buffer = []
  var that = this;
  
  req.on('data',function(data){
      buffer.push(data);
  
  });
  req.on('end',function(){
      var msgXml = Buffer.concat(buffer).toString('utf-8');

      parseString(msgXml,{explicitArray : false},function(err,result){
          // 如果有错误直接抛出
          if(err) throw err;
          result = result.xml;
          var toUser = result.ToUserName; 
          var fromUser = result.FromUserName;
          console.log(result)
          // 判断消息类型
          if(result.MsgType === "event") {
              // 关注微信公众号
              if(result.Event === "subscribe") {
                var resultXml = createTextRes(fromUser,toUser, "欢迎来到林俊杰的公众号")
                res.send(resultXml);
              }
          }else {
              let response = "默认"
              switch(result.MsgType){
                case "text":
                  if(result.Content == "浙江工商大学"){
                    let {title,description,picurl,url} = store["浙江工商大学"]
                    res.send(createOneArticleRes(fromUser,toUser,title,description,picurl,url)).then(res=>{
                      console.log('成功了：hhh', res)
                    },err=>{
                      console.log("失败了:", err)
                    })
                  }else if(result.Content == "学号"){      
                    res.send(createTextRes(fromUser,toUser,1905090226));
                  }else if(result.Content == 'code'){
                    let link = '<a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx163c1f019c9b0082&redirect_uri=http://express-0i38-1740863-1310448763.ap-shanghai.run.tcloudbase.com/index.html&response_type=code&scope=snsapi_base&state=123#wechat_redirect">点击授权</a>'
                    res.send(createTextRes(FromUserName,toUser,link))
                  }else {
                    res.send(createTextRes(fromUser,toUser,result.Content));
                  }
                  break;
                case "location":
                  var info =  `${result.Label}:${result.Location_X}-${result.Location_Y}`
                  res.send(createTextRes(fromUser,toUser,info));
                  break;
                case "voice":
                  res.send(createTextRes(fromUser,toUser,"这是语音哦"));
                  break;
              }
            }
      })
  })
})
const port = process.env.PORT || 80;
async function bootstrap() {
  // await initDB();
  app.listen(port, () => {
    console.log("启动成功", port);
  });
}
bootstrap();
getAccessToken()
createMenu()